#!/usr/bin/python2

from socket import *
import time
import sys
import os
import re
import signal
import ConfigParser
import struct
import subprocess
import shutil
from subprocess import Popen

#sys.path.append('/lib/')
import rising_log

ROLLBACK_CONF = 'rollback_log.cfg'

### init log ###
global logger
logger = rising_log.init_log('rollback_log', 'msg_log.ini', 0, 0)

def _sig_INT_handle(signum, frame):
        logger.error("SIGINT recieve, exit()")
        sys.exit()
		
def dir_status(log_dir,used):

	syscmd = 'du -s %s'%(log_dir)
	
	output = Popen(syscmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
		
	output_err = output.stderr.readlines()
	output_out = output.stdout.readlines()
		
	if len(output_err) > 0:
		for line in output_err:
			logger.error("%s",line)
		logger.error("syscmd:%s failed",syscmd)
		return 0
			
	if len(output_out) > 0:
		for line in output_out:
			if log_dir in line:
				dir_used = int(line.split("\t")[0])/1024
						
	logger.info("dir used:%d, max:%d",dir_used,used)

	if dir_used > used:
		logger.info("disk used:%d to max:%d",dir_used,used)
		return -1
	return 0
		
def check_dir(data_dir):
	if not os.path.exists(data_dir):
		logger.error("no dir:%s,then create dir",data_dir)
		os.makedirs(data_dir)

def init_rollback_config(config_file):
	rollback_config = {}
	try:
		config = ConfigParser.ConfigParser()
		config.read(config_file)

		rollback_config['interval'] = config.get('conf', 'interval')
		rollback_config['day'] = config.get('conf', 'day')
		rollback_config['used'] = config.get('conf', 'used')
		rollback_config['log_dir'] = config.get('conf', 'log_dir')

	except Exception,msg:
		logger.error(str(msg).strip())
		sys.exit(1)

	return rollback_config


def rollback_log(log_dir,day,used):

	file_list = []
	logdir_list =[]

	file_list = os.listdir(log_dir)
	
	if len(file_list) <= 0:
		logger.debug("no log data in dir:%s",log_dir)
		return 0

	file_list.sort(reverse=True)
	dir_num = 0
	for i in file_list:
		logdir_name = os.path.join(log_dir, i)
		if os.path.isdir(logdir_name):
			dir_num = dir_num + 1
			if dir_num > day:
				logger.info("dir_num:%d, maxnum:%d",dir_num,day)
				logger.info("delete log dir:%s",logdir_name)
				shutil.rmtree(logdir_name)

			else:
				logdir_list.append(logdir_name)

	logdir_list.sort()
	del logdir_list[-1]

	for i in logdir_list:
		if dir_status(log_dir,used) < 0 :
			logger.info("delete log dir:%s",i)
			shutil.rmtree(i)
		else:
			break
	
	return 1

def main():
	signal.signal(signal.SIGINT, _sig_INT_handle)

	while(1):
		rollback_config = init_rollback_config(ROLLBACK_CONF)
	
		sleep_interval = int(rollback_config['interval'])
		log_dir = rollback_config['log_dir']
		day = int(rollback_config['day'])
		used = int(rollback_config['used'])

		rollback_log(log_dir,day,used)
		time.sleep(sleep_interval)

if __name__ == '__main__':
        main()

